/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */

package com.intelligent.ispc.client.core.view.analysis.spc;

import com.intelligent.ispc.client.core.modal.spc.TestItemSimpleModel;
import com.intelligent.ispc.client.ex.CheckBoxHeadRenderer;
import com.intelligent.ispc.client.ex.JTextFieldEx;
import com.intelligent.ispc.client.utils.GBC;
import com.intelligent.ispc.core.dto.TestItemDto;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

/**
 * Created by Peter on 2016/9/9.
 * Updated by Tony.yu on 2016/10/08.Added a method
 */
public class SpcExportMultipleItemDialog extends JDialog {
    private TestItemSimpleModel testItemModel;
    private java.util.List<RowFilter<Object, Object>> selectedFilterList;

    /**
     * Constructor
     */
    public SpcExportMultipleItemDialog() {
        initComponents();
    }

    /**
     * Initialize component
     */
    public void initComponents() {
        selectedCountLable = new JLabel();
        nextStepBtn = new JButton("NextStep");
        cancelBtn = new JButton("Cancel");
        selectedItemTable = new JTable();
        selectedItemFilterText = new JTextFieldEx();
        allItemTable = new JTable();
        allItemFilterText = new JTextFieldEx();
        testItemModel = new TestItemSimpleModel(new String[]{"check", "name"});

        selectedItemFilterText.setPlaceHolder("Filter");
        allItemFilterText.setPlaceHolder("Filter");

        this.setLayout(new GridBagLayout());


        JPanel selectedPanel = new JPanel(new GridBagLayout());
        selectedPanel.setBorder(BorderFactory.createTitledBorder("Selected Item"));
        JScrollPane selectedScroll = new JScrollPane();
        selectedScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        selectedScroll.setViewportView(selectedItemTable);

        selectedPanel.add(selectedCountLable, new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0));
        selectedPanel.add(selectedScroll, new GBC(0, 1).setFill(GBC.BOTH).setWeight(100, 100));
        selectedPanel.add(selectedItemFilterText, new GBC(0, 2).setFill(GBC.HORIZONTAL));

        JPanel allPanel = new JPanel(new GridBagLayout());
        allPanel.setBorder(BorderFactory.createTitledBorder("All Item"));
        JScrollPane allScroll = new JScrollPane();
        allScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        allScroll.setViewportView(allItemTable);

        allPanel.add(allScroll, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));
        allPanel.add(allItemFilterText, new GBC(0, 1).setFill(GBC.HORIZONTAL));

        JPanel btnPanel = new JPanel();
        btnPanel.setLayout(new GridBagLayout());
        btnPanel.add(new JPanel(), new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));
        btnPanel.add(nextStepBtn, new GBC(1, 0).setFill(GBC.HORIZONTAL).setInsets(10, 5, 5, 5));
        btnPanel.add(cancelBtn, new GBC(2, 0).setFill(GBC.HORIZONTAL).setInsets(10, 0, 5, 0));


        JLabel title = new JLabel("Select some items for export.");
        this.add(title, new GBC(0, 0).setFill(GBC.HORIZONTAL).setInsets(5));
        this.add(selectedPanel, new GBC(0, 1).setFill(GBC.BOTH).setWeight(100, 100).setInsets(5));
        this.add(allPanel, new GBC(0, 2).setFill(GBC.BOTH).setWeight(100, 100).setInsets(5));
        this.add(btnPanel, new GBC(0, 3).setFill(GBC.HORIZONTAL).setInsets(0));
        initView();
        initListener();
    }

    public JButton getNextStepBtnBtn() {
        return nextStepBtn;
    }

    /**
     * Get the selected test item names
     *
     * @return test item names list
     */
    public java.util.List<String> getSelectedItemName() {
        java.util.List<TestItemDto> testItems = testItemModel.getData();
        java.util.List<String> itemNames = new ArrayList<>();

        for (TestItemDto dto : testItems) {
            if (dto.getCheck()) {
                itemNames.add(dto.getName());
            }
        }

        return itemNames;
    }

    /**
     * Set data
     *
     * @param testItemNames test item names list
     */
    public void setData(java.util.List<String> testItemNames) {
        java.util.List<TestItemDto> data = new ArrayList();
        for (String name : testItemNames) {
            TestItemDto dto = new TestItemDto();
            dto.setCheck(false);
            dto.setName(name);
            data.add(dto);
        }
        testItemModel.setData(data);
        testItemModel.setViewData(getTableViewData());
    }

    public int getSelectedCount() {
        return testItemModel.getSelectedCount();
    }
    private void initView() {
        testItemModel.setData(new ArrayList());
        allItemSorter = new TableRowSorter(testItemModel);
        allItemTable.setModel(testItemModel);
        allItemTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        allItemTable.setRowSorter(allItemSorter);
        CheckBoxHeadRenderer renderer = new CheckBoxHeadRenderer(allItemTable);
        renderer.setCheckboxSelect(false);
        allItemTable.getTableHeader().setDefaultRenderer(renderer);

        allItemTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

        allItemTable.getColumnModel().getColumn(0).setPreferredWidth(25);
        allItemTable.getColumnModel().getColumn(0).setMaxWidth(50);
        allItemTable.getColumnModel().getColumn(1).setPreferredWidth(100);


        selectedItemSorter = new TableRowSorter(testItemModel);
        selectedItemTable.setModel(testItemModel);
        selectedItemTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        selectedItemTable.setRowSorter(selectedItemSorter);

        selectedItemTable.getTableHeader().setVisible(false);
        DefaultTableCellRenderer renderer2 = new DefaultTableCellRenderer();
        renderer2.setPreferredSize(new Dimension(0, 0));
        selectedItemTable.getTableHeader().setDefaultRenderer(renderer2);
        selectedItemTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

        selectedItemTable.getColumnModel().getColumn(0).setPreferredWidth(10);
        selectedItemTable.getColumnModel().getColumn(0).setMaxWidth(50);
        selectedItemTable.getColumnModel().getColumn(1).setPreferredWidth(100);

        selectedFilterList = new ArrayList<RowFilter<Object, Object>>();
        selectedFilterList.add(RowFilter.regexFilter("true", 0));
        selectedFilterList.add(RowFilter.regexFilter("", 1));
        selectedItemSorter.setRowFilter(RowFilter.andFilter(selectedFilterList));
        selectedCountLable.setText("Count: " + testItemModel.getSelectedCount());

        testItemModel.onCheckChange(new TestItemSimpleModel.CheckChangeEvent() {
            @Override
            public void change() {
                testItemModel.setViewData(getTableViewData());
                selectedCountLable.setText("Count: " + testItemModel.getSelectedCount());
            }
        });
    }

    private void initListener() {
        SpcExportMultipleItemDialog d = this;
        cancelBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                d.setVisible(false);
            }
        });
        allItemTable.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = ((JTable) e.getSource()).rowAtPoint(e.getPoint());
                int col = ((JTable) e.getSource()).columnAtPoint(e.getPoint());
                int rowIndex = ((JTable) e.getSource()).convertRowIndexToModel(row);
                int colIndex = ((JTable) e.getSource()).convertColumnIndexToModel(col);
                selectItem(rowIndex, colIndex);
                testItemModel.setViewData(getTableViewData());
            }
        });
        allItemFilterText.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                update(e);
            }

            private void update(DocumentEvent e) {
                String value = allItemFilterText.getText();
                if (value.length() == 0) {
                    allItemSorter.setRowFilter(null);
                } else {
                    allItemSorter.setRowFilter(RowFilter.regexFilter(value, 1));
                }
                testItemModel.setViewData(getTableViewData());
            }
        });

        selectedItemTable.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = ((JTable) e.getSource()).rowAtPoint(e.getPoint());
                int col = ((JTable) e.getSource()).columnAtPoint(e.getPoint());
                int rowIndex = ((JTable) e.getSource()).convertRowIndexToModel(row);
                int colIndex = ((JTable) e.getSource()).convertColumnIndexToModel(col);
                selectItem(rowIndex, colIndex);
            }
        });

        selectedItemFilterText.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                update(e);
            }

            private void update(DocumentEvent e) {
                String value = selectedItemFilterText.getText();
                if (value.length() == 0) {
                    selectedFilterList.set(1, RowFilter.regexFilter("", 1));
                } else {
                    selectedFilterList.set(1, RowFilter.regexFilter(value, 1));
                }
                selectedItemSorter.setRowFilter(RowFilter.andFilter(selectedFilterList));
            }
        });
    }

    private void selectItem(int row, int col) {
        if ((Boolean) testItemModel.getValueAt(row, 0)) {
            testItemModel.setValueAt(false, row, 0);
        } else {
            testItemModel.setValueAt(true, row, 0);
        }
        selectedCountLable.setText("Count: " + testItemModel.getSelectedCount());
        selectedItemSorter.sort();
        allItemTable.updateUI();
        selectedItemTable.updateUI();
    }

    /**
     * Set the checkBox is not selected
     *
     * @param isChecked true or false
     */
    public void setCheckboxUnSelect(boolean isChecked) {
        ((CheckBoxHeadRenderer) allItemTable.getTableHeader().getDefaultRenderer()).setCheckboxSelect(isChecked);
    }

    /**
     * Get table view data
     *
     * @return new row count
     */
    public int[] getTableViewData() {
        int[] items = new int[allItemTable.getRowCount()];
        int i;
        for (i = 0; i < allItemTable.getRowCount(); i++) {
            items[i] = allItemTable.convertRowIndexToModel(i);
        }
        return items;
    }

    public void cleanFilter() {
        selectedItemFilterText.setText("");
        allItemFilterText.setText("");
    }

    private JTable selectedItemTable;
    private JTable allItemTable;
    private JTextFieldEx selectedItemFilterText;
    private JTextFieldEx allItemFilterText;
    private TableRowSorter allItemSorter;
    private TableRowSorter selectedItemSorter;
    private JLabel selectedCountLable;
    private JButton nextStepBtn;
    private JButton cancelBtn;
}
